package edu.dayu.demoNetty2;

import edu.dayu.demoNetty1.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

public class HttpServer {
    public static void main(String[] args) {
        /**
         * 创建 BoosGroup 和 WorkerGroup
         * boos 负责处理连接，worker 负责业务逻辑
         */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建服务器端的启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // 使用NioSocketChannel 作为服务器的通道实现
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 给 pipeline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //向管道加入处理器
                            //得到管道
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入一个 netty 提供的 httpServerCodec codec =>[coder - decoder]
                            //HttpServerCodec 说明
                            //1. HttpServerCodec 是 netty 提供的处理 http 的 编-解码器
                            pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
                            //2. 增加一个自定义的 handler
                            pipeline.addLast("MyTestHttpServerHandler", new TestHttpServerHandler());
                        }
                    });
            System.out.println("服务器 is ready");
            // 启动服务器并绑定端口
            ChannelFuture cf = bootstrap.bind(6668).sync();
            // 关闭通道进行监听
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
